import { getSetting,openSetting,chooseAddress,showModal,showToast,requestPayment } from "../../utils/asyncWX";
import regeneratorRuntime, { async } from '../../lib/runtime/runtime';
import { request } from '../../request/index'/* 发请求 */

Page({
    /**页面的初始数据*/
    data: {
        addressShow:{},
        cart:[],
        totalPrice:0,
        totalNum:0
    },
    /* 生命周期函数--监听页面显示 */
     onShow: function (options) {
        let addressShow = wx.getStorageSync('address');
        let cart = wx.getStorageSync('cart')||[];
        let totalPrice = 0
        let totalNum = 0
        console.log(cart);
        console.log(addressShow);
        /* 直接在这次遍历中加入 全选判断 */
        /* forEach ()方法没有返回值，会修改原来的数组 */
        cart = cart.filter(v=>v.checked)
        cart.forEach(v => {
            if (v.checked) {
                totalPrice += v.goods_price*v.num
                totalNum += v.num
            }
        });
        this.setData({
            addressShow,
            cart,
            totalPrice,
            totalNum
        })
    },
    async handlePayMon(){
        try {
            const token = wx.getStorageSync('token')
            /* 无token无法发起 支付请求 */
            /* if (!token) {
                wx.navigateTo({
                    url: '/pages/auth/auth'
                });
                return
            } */
            /* 请求头  加token */
            // const header = {Authorization:token}
            const consignee_addr = this.data.addressShow.all
            const order_price = this.data.totalPrice
            const cart = this.data.cart
            let goods=[]
            cart.forEach(v=>goods.push({
                goods_id:v.goods_id,
                goods_number:v.goods_number,
                goods_price:v.goods_price
            }))
            /* 请求体 */
            const orderParams = {consignee_addr,order_price,goods}
            /* 发起创建订单，获取 订单编号 */
            const {order_number} = await request({
                url:'/my/orders/create',
                data:orderParams,
                method:"post"
            })
            
            /* 发起预支付接口 */
            const {pay} = await request({
                url:'/my/orders/req_unifiedorder',
                data:{order_number},
                method:"post"
            })
            /* 发起微信支付 */
            await requestPayment({pay})
            /* 查询后台订单状态 */
            const {res} = await request({
                url:'/my/orders/chkOrder',
                data:{order_number},
                method:"post"
            })
            await showToast({title: '支付成功'});
            /* 支付成功后购物车删除商品 */
            let newCart = wx.getStorageSync("cart");
            newCart =  newCart.filter(v=>!v.checked)
            wx.setStorageSync("cart", newCart);
            wx.navigateTo({url: '/pages/order/order'});
        } catch (error) {
            await showToast({title: '支付失败'});
            console.log(error);
        }
    }
})